﻿using DataAchive.Common;
using DataAchive.Extend;
using DataAchive.Helper;
using DataAchive.Model.Excel.Export;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.UI;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;


namespace DataAchive
{
    /// <summary>
    /// WindowShow.xaml 的交互逻辑
    /// </summary>
    public partial class WindowShow : Window
    {

        //
        private Timer _timer;
        private static string _directoryName = "Reports";
        private static Dictionary<string, string> _pairs = null;     
        private TimeSpan beginSpan;
        private TimeSpan endSpan;

        public WindowShow()
        {

            InitializeComponent();
            ConnectionHelper.GetXmlSetting();
            var beginTime = Setting.GetXmlNode("setting/DateReport/BeginTime");
            var endTime = Setting.GetXmlNode("setting/DateReport/EndTime");
            SetTime(beginTime.InnerText,endTime.InnerText);

            siteAddress.ItemsSource = ConnectionHelper.siteAndConnections;
            siteAddress.DisplayMemberPath = "Key";
            siteAddress.SelectedValuePath = "Value";
            if (ConnectionHelper.siteAndConnections.Count > 0)
            {
                siteAddress.SelectedIndex = 0;
            }

            _pairs = ConnectionHelper.siteAndConnections.ToDictionary(x => x.Key, y => y.Value);
            _timer = new Timer(CreateReport, null, 1000, 60 * 1000);
        }

        private void SetTime(string begin,string end)
        {
             beginSpan = new TimeSpan(8, 30, 0);
             endSpan = new TimeSpan(8, 30, 0);
            try
            {              

                TimeSpan.TryParse(begin, out beginSpan);
                TimeSpan.TryParse (end, out endSpan);
            }
            catch (Exception e)
            {
                SoftCommon.Log.Write("time trans err:"+e.Message);
                 beginSpan = new TimeSpan(8, 30, 0);
                 endSpan = new TimeSpan(8, 30, 0);
            }

        }

        private void mainWinBtn_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(ConnectionHelper.CurrentSiteAddress))
            {
                MessageBox.Show("请选择集控室编号");
                return;
            }
            NgInfoWindow ngInfoWindow = new NgInfoWindow();
            ngInfoWindow.Closed += (s, args) =>
            {
                this.IsEnabled = true;
            };
            ngInfoWindow.Show();

            this.IsEnabled = false;
        }



        private void exportWinBtn_Click(object sender, RoutedEventArgs e)
        {
            ReportShow reportShow = new ReportShow();
            reportShow.Show();
        }

        private void siteAddress_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var address = siteAddress.SelectedValue;
            SoftCommon.Log.Write("siteaddress：" + address);
            ConnectionHelper.CurrentSiteAddress = address?.ToString();
        }


        private void CreateReport(object state)
        {
            var yesterday = DateTime.Now.AddDays(-1);
            var now = DateTime.Now;
            var  _startTime = new DateTime(yesterday.Year, yesterday.Month, yesterday.Day, beginSpan.Hours, beginSpan.Minutes, beginSpan.Seconds);
            var _endTime = new DateTime(now.Year, now.Month, now.Day, endSpan.Hours, endSpan.Minutes, endSpan.Seconds);

            if (_pairs == null || _pairs.Count == 0)
            {
                SoftCommon.Log.Write("Setting.xml未配置有效的集控室地址信息.");
                return;
            }
            //over 9.. 
            var extime = _endTime.AddMinutes(30);
            if (DateTime.Now.Hour == extime.Hour && DateTime.Now.Minute == extime.Minute)
            {
                SoftCommon.Log.Write($"now time is.{DateTime.Now}");
                var datestr = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
                var filePath = Path.Combine(Environment.CurrentDirectory, _directoryName, datestr);
                if (Directory.Exists(filePath))
                {
                    if (Directory.GetFiles(filePath).Length >= _pairs.Count)
                    {
                        SoftCommon.Log.Write("已经存在报表.");
                        return;
                    }

                }
                else
                {
                    Directory.CreateDirectory(filePath);
                }
                // sql

                WhereQ whereQ = new WhereQ()
                {
                    BeginTime = _startTime,
                    EndTime = _endTime,

                };

                ///
                foreach (var itemPair in _pairs)
                {

                    try
                    {
                        CreateRowCol(whereQ, itemPair.Value, filePath);
                        SoftCommon.Log.Write("add new report file.");
                        Thread.Sleep(20);
                    }
                    catch (Exception e)
                    {
                        SoftCommon.Log.Write(itemPair.Value + e.Message);
                        Thread.Sleep(50);
                        continue;
                    }

                }






            }
        }

        //行列表
        static void CreateRowCol(WhereQ query, string address, string dirPath)
        {
            //var dstail = ReportHelper.GetColRowReportInfo(query, address, false);
            //var dtval = ReportHelper.DetailReportTrans(dstail.Tables[0]);
            //var lsresult = ReportHelper.DicColRowToList(dtval);
            //lsresult.ForEach(x =>
            //{

            //    var min_max = ReportShow.FindMaxTime(x.ElCreateTime, x.VICreateTime, x.VBCreateTime);
            //    var max = ReportShow.FindMaxTime(x.ElFinishTime, x.VIFinishTime, x.VBFinishTime);
            //    if (min_max == DateTime.MinValue || max == DateTime.MinValue)
            //    {

            //    }
            //    else
            //    {
            //        x.HumanJudgeTime = max - min_max;
            //    }
            //    var direc = ReportShow.isDirectRes(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult);
            //    x.IsDirect = direc ? "是" : "否";
            //    if (direc)
            //    {
            //        x.HumanJudgeTime = TimeSpan.Zero;
            //    }
            //    int aiR = ReportShow.noNullResult(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult);
            //    int RenR = ReportShow.noNullResult(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult);
            //    if (aiR == RenR)
            //    {
            //        if (aiR == 1)
            //        {
            //            x.LouJianOrGuopan = ReportShow.louWu(
            //                ReportShow.noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
            //                ReportShow.noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0]
            //                );
            //        }
            //        else if (aiR == 2)
            //        {
            //            x.LouJianOrGuopan = ReportShow.louWu(
            //              ReportShow.noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
            //                ReportShow.noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[1],
            //              ReportShow.noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0],
            //                 ReportShow.noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[1]
            //              );
            //        }
            //        else if (aiR == 3)
            //        {
            //            x.LouJianOrGuopan = ReportShow.louWu(
            //              ReportShow.noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
            //                ReportShow.noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[1],
            //                 ReportShow.noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[2],
            //              ReportShow.noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0],
            //                 ReportShow.noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[1],
            //                   ReportShow.noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[2]
            //              );
            //        }
            //    }

            //    List<string> aielInfoList = new List<string>();

            //    if (!string.IsNullOrWhiteSpace(x.ElAiDetectInfo))
            //    {
            //        string[] allQx = x.ElAiDetectInfo.Split(' ');
            //        foreach (var item in allQx)
            //        {
            //            var shuzu = item.Split(':');
            //            if (shuzu.Length == 2)
            //            {
            //                aielInfoList.Add(shuzu[1]);
            //            }
            //            else if (shuzu.Length > 2)
            //            {
            //                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
            //                aielInfoList.Add(shuzu[1]);
            //            }
            //        }
            //    }
            //    aielInfoList = aielInfoList.Distinct().ToList();
            //    x.ElAiDetectInfo = string.Join(",", aielInfoList);

            //    List<string> aiviInfoList = new List<string>();

            //    if (!string.IsNullOrWhiteSpace(x.ViAiDetectInfo))
            //    {
            //        string[] allQx = x.ViAiDetectInfo.Split(' ');
            //        foreach (var item in allQx)
            //        {
            //            var shuzu = item.Split(':');
            //            if (shuzu.Length == 2)
            //            {
            //                aiviInfoList.Add(shuzu[1]);
            //            }
            //            else if (shuzu.Length > 2)
            //            {
            //                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
            //                aiviInfoList.Add(shuzu[1]);
            //            }
            //        }
            //    }
            //    aiviInfoList = aiviInfoList.Distinct().ToList();
            //    x.ViAiDetectInfo = string.Join(",", aiviInfoList);

            //    List<string> aivbInfoList = new List<string>();
            //    if (!string.IsNullOrWhiteSpace(x.VBAiDetectInfo))
            //    {
            //        string[] allQx = x.VBAiDetectInfo.Split(' ');
            //        foreach (var item in allQx)
            //        {
            //            var shuzu = item.Split(':');
            //            if (shuzu.Length == 2)
            //            {
            //                aivbInfoList.Add(shuzu[1]);
            //            }
            //            else if (shuzu.Length > 2)
            //            {
            //                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
            //                aivbInfoList.Add(shuzu[1]);
            //            }
            //        }
            //    }
            //    aivbInfoList = aivbInfoList.Distinct().ToList();
            //    x.VBAiDetectInfo = string.Join(",", aivbInfoList);

            //});
            var lsresult= GetColRowReportsCommon(query,address);
            var _dress = address.Split(';')[0];
            string fileName = $@"{dirPath}\{_dress}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.csv";
            ReportExport<ColRowReport>.ExportCsv(lsresult, fileName);
            SoftCommon.Log.Write($"导出{fileName}结束");

        }

      public static List<ColRowReport> GetColRowReportsCommon(WhereQ query, string address)
        {
            var dstail = ReportHelper.GetColRowReportInfo(query, address, false);
            var dtval = ReportHelper.DetailReportTrans(dstail.Tables[0]);
            var lsresult = ReportHelper.DicColRowToList(dtval);
            lsresult.ForEach(x =>
            {

                var min_max = ReportShow.FindMaxTime(x.ElCreateTime, x.VICreateTime, x.VBCreateTime);
                var max = ReportShow.FindMaxTime(x.ElFinishTime, x.VIFinishTime, x.VBFinishTime);
                if (min_max == DateTime.MinValue || max == DateTime.MinValue)
                {

                }
                else
                {
                    x.HumanJudgeTime = max - min_max;
                }
                var direc = ReportShow.isDirectRes(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult);
                x.IsDirect = direc ? "是" : "否";
                if (direc)
                {
                    x.HumanJudgeTime = TimeSpan.Zero;
                }
                int aiR = ReportShow.noNullResult(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult);
                int RenR = ReportShow.noNullResult(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult);
                if (aiR == RenR)
                {
                    if (aiR == 1)
                    {
                        x.LouJianOrGuopan = ReportShow.louWu(
                            ReportShow.noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                            ReportShow.noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0]
                            );
                    }
                    else if (aiR == 2)
                    {
                        x.LouJianOrGuopan = ReportShow.louWu(
                          ReportShow.noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                            ReportShow.noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[1],
                          ReportShow.noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0],
                             ReportShow.noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[1]
                          );
                    }
                    else if (aiR == 3)
                    {
                        x.LouJianOrGuopan = ReportShow.louWu(
                          ReportShow.noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                            ReportShow.noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[1],
                             ReportShow.noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[2],
                          ReportShow.noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0],
                             ReportShow.noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[1],
                               ReportShow.noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[2]
                          );
                    }
                }

                List<string> aielInfoList = new List<string>();

                if (!string.IsNullOrWhiteSpace(x.ElAiDetectInfo))
                {
                    string[] allQx = x.ElAiDetectInfo.Split(' ');
                    foreach (var item in allQx)
                    {
                        var shuzu = item.Split(':');
                        if (shuzu.Length == 2)
                        {
                            aielInfoList.Add(shuzu[1]);
                        }
                        else if (shuzu.Length > 2)
                        {
                            SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                            aielInfoList.Add(shuzu[1]);
                        }
                    }
                }
                aielInfoList = aielInfoList.Distinct().ToList();
                x.ElAiDetectInfo = string.Join(",", aielInfoList);

                List<string> aiviInfoList = new List<string>();

                if (!string.IsNullOrWhiteSpace(x.ViAiDetectInfo))
                {
                    string[] allQx = x.ViAiDetectInfo.Split(' ');
                    foreach (var item in allQx)
                    {
                        var shuzu = item.Split(':');
                        if (shuzu.Length == 2)
                        {
                            aiviInfoList.Add(shuzu[1]);
                        }
                        else if (shuzu.Length > 2)
                        {
                            SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                            aiviInfoList.Add(shuzu[1]);
                        }
                    }
                }
                aiviInfoList = aiviInfoList.Distinct().ToList();
                x.ViAiDetectInfo = string.Join(",", aiviInfoList);

                List<string> aivbInfoList = new List<string>();
                if (!string.IsNullOrWhiteSpace(x.VBAiDetectInfo))
                {
                    string[] allQx = x.VBAiDetectInfo.Split(' ');
                    foreach (var item in allQx)
                    {
                        var shuzu = item.Split(':');
                        if (shuzu.Length == 2)
                        {
                            aivbInfoList.Add(shuzu[1]);
                        }
                        else if (shuzu.Length > 2)
                        {
                            SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                            aivbInfoList.Add(shuzu[1]);
                        }
                    }
                }
                aivbInfoList = aivbInfoList.Distinct().ToList();
                x.VBAiDetectInfo = string.Join(",", aivbInfoList);

            });
            return lsresult;
        }

        //缺陷汇总基础信息
        static void CreateQuexianHuiZong(WhereQ query, string address, string dirPath)
        {
           
            var lsresult = GetColRowReportsCommon(query, address);
            var reportDefectData = AiDefectStaticRRR.GetHReportDataAi(lsresult);
            var _dress = address.Split(';')[0];
            string fileName = $@"{dirPath}\{_dress}_缺陷汇总基础信息_{DateTime.Now.ToString("yyyyMMddHHmmss")}.csv";
            ReportExport<AiDefectStaticColumnAiC>.ExportCsv(reportDefectData, fileName);
            SoftCommon.Log.Write($"导出{fileName}结束");

        }

        //缺陷汇总误检信息
        static void CreateQuexianWujian(WhereQ query, string address, string dirPath)
        {

            var lsresult = GetColRowReportsCommon(query, address);
            var reportDefectData = AiDefectStaticRRR.GetHReportDataHuman(lsresult);
            var _dress = address.Split(';')[0];
            string fileName = $@"{dirPath}\{_dress}_缺陷汇总误检信息_{DateTime.Now.ToString("yyyyMMddHHmmss")}.csv";
            ReportExport<AiDefectStaticColumnHumanC>.ExportCsv(reportDefectData, fileName);
            SoftCommon.Log.Write($"导出{fileName}结束");

        }


        //缺陷占比信息
        static void CreateQuexianBiLv(WhereQ query, string address, string dirPath)
        {

            var lsresult = GetColRowReportsCommon(query, address);
            var reportDefectData = AiDefectStaticRRR.GetHReportDataAi11111(lsresult);
            var totalDefectNumber = reportDefectData.Sum(x => x.DefectCount);
            List<DefectRateStaticColumn> defectRateStaticColumns = new List<DefectRateStaticColumn>();
            foreach (var item in reportDefectData)
            {
                DefectRateStaticColumn defectRateStatic = new DefectRateStaticColumn()
                {
                    DefectCount = item.DefectCount,
                    DefectName = item.DefectName,
                    DefectRate = totalDefectNumber == 0 ? 0 : Math.Round((decimal)item.DefectCount / totalDefectNumber, 4)
                };
                defectRateStaticColumns.Add(defectRateStatic);
            }
            var _dress = address.Split(';')[0];
            string fileName = $@"{dirPath}\{_dress}_缺陷占比信息_{DateTime.Now.ToString("yyyyMMddHHmmss")}.csv";
            ReportExport<DefectRateStaticColumn>.ExportCsv(defectRateStaticColumns, fileName);
            SoftCommon.Log.Write($"导出{fileName}结束");

        }

        //总比率信息
        static void CreateZongBiLv(WhereQ query, string address, string dirPath)
        {

            var lsresult = GetColRowReportsCommon(query, address);
            var totalNum = lsresult.Count();
            var zhitong = lsresult.Count(x => x.HumanJudgeTime != null && x.HumanJudgeTime == TimeSpan.Zero);
            var wupan = lsresult.Count(x => !string.IsNullOrWhiteSpace(x.LouJianOrGuopan) && x.LouJianOrGuopan.Equals("过判"));
            var ng = lsresult.Count(x => !string.IsNullOrWhiteSpace(x.LouJianOrGuopan) && x.LouJianOrGuopan.Equals("NG"));
           
            DataStaticsRate dataStaticsRate = new DataStaticsRate()
            {
                DirectRate = totalNum == 0 ? 0 : Math.Round((decimal)zhitong / totalNum, 4),
                TotalFaultRate = totalNum == 0 ? 0 : Math.Round((decimal)wupan / totalNum, 4),
                ProductNumber = totalNum,
                AiNG = totalNum - zhitong,
                HumanNG = ng
            };
        
            var _dress = address.Split(';')[0];
            string fileName = $@"{dirPath}\{_dress}_总比率信息_{DateTime.Now.ToString("yyyyMMddHHmmss")}.csv";
            ReportExport<DataStaticsRate>.ExportCsv(new List<DataStaticsRate>() { dataStaticsRate }, fileName);
            SoftCommon.Log.Write($"导出{fileName}结束");

        }

        private void localWinBtn_Click(object sender, RoutedEventArgs e)
        {
            ReportShowLocal reportShowLocal = new ReportShowLocal();
            reportShowLocal.Show();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            DataShowWindow sw = new DataShowWindow();
            sw.ShowDialog();
        }

        private void msBtn_Click(object sender, RoutedEventArgs e)
        {
            DataShowMachinedWindow sw = new DataShowMachinedWindow();
            sw.ShowDialog();
        }
    }
}
